using System;
using System.Linq;
using Granite.Collections;
using Toon.Models.Catalogs;
using System.Xml.Linq;
using System.Collections.Generic;
using Granite.Modeling;
using System.Collections.Specialized;
using System.ComponentModel;
using Granite.Eventing;

namespace Toon.Models.Characters
{
	public class ShitckCollection : ChangeTrackingModelCollection<Shitck>
	{
		/// <summary>
		/// Initializes a new instance of the ShitckCollection class.
		/// </summary>
		public ShitckCollection()
		{
			CollectionChanged += ShitckCollection_CollectionChanged;
			ItemPropertyChanged += ShitckCollection_ItemPropertyChanged;
		}

		public int SkillPointsSpent
		{
			get
			{
				var points = this.Sum(s => s.SkillPoints);
				if (Count > 1)
					points += (Count - 1) * 5; //todo: move this formula to the rules
				return points;
			}
		}

		public Shitck Add(ShitckDefinition definition)
		{
			var result = new Shitck(definition);
			Add(result);
			return result;
		}

		public Shitck AddNew()
		{
			return Add(new ShitckDefinition("New Shitck", 0, ""));
		}

		internal IList<XElement> ToXml()
		{
			return (from s in this select s.ToXml()).ToList();
		}

		internal void FromXml(XElement source)
		{
			foreach (var node in source.Elements("Shitck"))
				Add(Shitck.FromXml(node));
		}

		void ShitckCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			OnPropertyChanged("SkillPointsSpent");
		}

		private void ShitckCollection_ItemPropertyChanged(object sender, RelayedEventArgs<PropertyChangedEventArgs> e)
		{
			OnPropertyChanged("SkillPointsSpent");
		}


	}
}
